package com.tanhua.app.service;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.tanhua.app.exception.BusinessException;
import com.tanhua.app.exception.ErrorResult;
import com.tanhua.app.interceptor.UserHolder;
import com.tanhua.config.template.OssTemplate;
import com.tanhua.dubbo.api.SoundApi;
import com.tanhua.dubbo.api.SoundTimesApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.pojo.Sound;
import com.tanhua.model.pojo.SoundTimes;
import com.tanhua.model.pojo.UserInfo;
import com.tanhua.model.vo.SoundVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class PeachblossomService {

    @DubboReference
    private SoundApi soundApi;

    @DubboReference
    private SoundTimesApi soundTimesApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    //发送语音
    public void sendSound(MultipartFile multipartFile) throws Exception {
        //将语音消息传到oss中
        String soundUrl = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
        //将语音信息保存到数据库中
        String ret = soundApi.saveOrUpdate(soundUrl, UserHolder.getUserId());
        if (StringUtils.isNotBlank(ret)){
            throw new RuntimeException(ret);
        }
    }

    //接收语音
    public SoundVo receiveSound() {
        //查询登录用户的接收次数 没有次数不给接收语音
        SoundTimes soundTimes = soundTimesApi.findById(UserHolder.getUserId());
        if (soundTimes.getReceivetimes() <= 0){
            throw new BusinessException(ErrorResult.myError("今日接收次数已达到限制,请明天再试"));
        }
        soundTimes.setReceivetimes(soundTimes.getReceivetimes()-1);
        soundTimesApi.update(soundTimes);
        //随机挑选一条语音
        Sound sound = soundApi.getOne();
        //删除语音信息
        soundApi.delete(sound);
        //查询语音发送者的用户详细信息
        UserInfo userInfo = userInfoApi.findById(sound.getUserId());
        //封装结果返回数据
        SoundVo vo = SoundVo.init(userInfo, sound, soundTimes);
        return vo;
    }

    //每日定时执行任务
    public void dayTask() {
        //每日重置次数
        soundTimesApi.resetTimes();
    }
}
